/*
 * @lc app=leetcode.cn id=714 lang=javascript
 *
 * [714] 买卖股票的最佳时机含手续费
 */

// @lc code=start
/**
 * @param {number[]} prices
 * @param {number} fee
 * @return {number}
 */
var maxProfit = function (prices, fee) {
  const n = prices.length;
  let buy = prices[0] + fee;
  let profit = 0;
  for (let i = 1; i < n; i++) {
    // 今天价格比购买费用高，则有利润
    if (prices[i] > buy) {
      profit += prices[i] - buy;
      buy = prices[i];
      // 今天如果购买价比之前的购买价低，就更新购买价
    } else if (prices[i] + fee < buy) {
      buy = prices[i] + fee;
    }
  }
  return profit;
};
// @lc code=end
